package com.example.mybatisplusdemo.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplusdemo.Methods.methods;
import com.example.mybatisplusdemo.Result.Result;
import com.example.mybatisplusdemo.Service.*;
import com.example.mybatisplusdemo.pojo.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/api")
@CrossOrigin
@Validated
public class CartController {
    @Resource
    UserService userService;
    @Resource
    CartService cartService;
    @Resource
    BusinessService businessService;
    @Resource
    CateService cateService;
    @Resource
    GoodService goodService;
    @Resource
    OrderService orderService;

    /**
     * 分页和首页加购
     * @param token
     * @param userid
     * @param goodid
     * @return
     */
    @PostMapping("/addcart")
    public Result addcart(@Valid @NotBlank(message = "token不能为空")@RequestParam("token") String token,
                          @Valid @NotBlank(message = "id不能为空")@RequestParam("userid") String userid,
                          @Valid @NotBlank(message = "物品id不能为空")@RequestParam("goodid") String goodid){
        if (!userService.checktoken(token)){
            return new Result(400,"权限不足");
        }
        int count = cartService.count(new QueryWrapper<Cart>().eq("userid",userid).eq("goodid",goodid));
        if (count == 0){
            Cart cart = new Cart();
            cart.setUserid(userid);
            cart.setGoodid(goodid);
            cart.setNum("1");
            cartService.save(cart);
            return new Result(200,"添加成功");
        }else{
            Cart cart = cartService.getOne(new QueryWrapper<Cart>().eq("userid",userid).eq("goodid",goodid));
            cart.setNum(String.valueOf(Integer.parseInt(cart.getNum())+1));
            boolean isUpdate = cartService.update(cart,new QueryWrapper<Cart>().eq("id",cart.getId()));
            if (isUpdate){return new Result(200,"已在购物车中,加购成功");}
            else{return new Result(400,"加购失败");}
        }
    }

    /**
     * 获取用户个人信息
     * @param token
     * @param id
     * @return
     */
    @GetMapping("/getusercart")
    public Result getusercart(@RequestParam("token") String token,
                              @RequestParam("userid") String id){
        if (!userService.checktoken(token)){
            return new Result(400,"权限不足");
        }
        List<Cart> list = cartService.list(new QueryWrapper<Cart>().eq("userid",id));
        list.forEach(item->{
           item.setGoodname(goodService.getOne(new QueryWrapper<Good>().eq("id",item.getGoodid())).getName());
        });
        return new Result(200,"get",list);
    }

    /**
     * 商品加一
     * @param token
     * @param cartid
     * @return
     */
    @PostMapping("/cartaddone")
    public Result cartaddone(@Valid @NotBlank(message = "token不能为空")@RequestParam("token") String token,
                             @Valid @NotBlank(message = "物品id不能为空")@RequestParam("cartid") String cartid){
        if (!userService.checktoken(token)){
            return new Result(400,"权限不足");
        }
        Cart cart = cartService.getOne(new QueryWrapper<Cart>().eq("id",cartid));
        cart.setNum(String.valueOf(Integer.parseInt(cart.getNum())+1));
        boolean isUpdate = cartService.update(cart,new QueryWrapper<Cart>().eq("id",cartid));
        if (isUpdate) {return new Result(200,"添加成功");}
        else {return new Result(400,"添加失败,请稍后再试");}
    }

    /**
     * 商品减一
     * @param token
     * @param cartid
     * @return
     */
    @PostMapping("/cartreduceone")
    public Result cartreduceone(@Valid @NotBlank(message = "token不能为空")@RequestParam("token") String token,
                                @Valid @NotBlank(message = "物品id不能为空")@RequestParam("cartid") String cartid){
        if (!userService.checktoken(token)){
            return new Result(400,"权限不足");
        }
        Cart cart = cartService.getOne(new QueryWrapper<Cart>().eq("id",cartid));
        cart.setNum(String.valueOf(Integer.parseInt(cart.getNum())-1));
        boolean isUpdate = cartService.update(cart,new QueryWrapper<Cart>().eq("id",cartid));
        if (isUpdate) {return new Result(200,"减少成功");}
        else {return new Result(400,"减少失败,请稍后再试");}
    }

    /**
     * 删除购物车的物品
     * @param token
     * @param cartid
     * @return
     */
    @PostMapping("/userdeletecart")
    public Result userdeletecart(@Valid @NotBlank(message = "token不能为空")@RequestParam("token") String token,
                                 @Valid @NotBlank(message = "物品id不能为空") @RequestParam("cartid") String cartid){
        if (!userService.checktoken(token)){
            return new Result(400,"权限不足");
        }
        boolean isDelete = cartService.remove(new QueryWrapper<Cart>().eq("id",cartid));
        if (isDelete){return new Result(200,"移除成功");}
        else{return new Result(400,"移除失败");}
    }

    /**
     * 计算购物车总价
     * @param token
     * @param id
     * @return
     */
    @GetMapping("/getprice")
    public Result getprice(@RequestParam("token") String token,
                           @RequestParam("userid") String id){
        if (!userService.checktoken(token)){
            return new Result(400,"权限不足");
        }
        AtomicInteger price = new AtomicInteger();
        List<Cart> list = cartService.list(new QueryWrapper<Cart>().eq("userid",id));
        list.forEach(item->{
            Good good = goodService.getOne(new QueryWrapper<Good>().eq("id",item.getGoodid()));
            price.addAndGet(Integer.parseInt(good.getPrice()) * Integer.parseInt(item.getNum()));
        });
        return new Result(200,"get",price);
    }

    /**
     * 创建订单
     * @param token
     * @param userid
     * @return
     */
    @PostMapping("/createorder")
    public Result createorder(@Valid @NotBlank(message = "token不能为空")@RequestParam("token") String token,
                              @Valid @NotBlank(message = "id不能为空")@RequestParam("userid") String userid){
        if (!userService.checktoken(token)){
            return new Result(400,"权限不足");
        }
        List<Cart> list = cartService.list(new QueryWrapper<Cart>().eq("userid",userid));
        list.forEach(item->{
            Order order = new Order();
            User user = userService.getOne(new QueryWrapper<User>().eq("id",userid));
            Good good = goodService.getOne(new QueryWrapper<Good>().eq("id",item.getGoodid()));
            order.setOrdernum(new methods().randomstr(7));
            order.setGoods(good.getName());
            order.setUserid(userid);
            order.setBusid(good.getBusid());
            order.setCreatetime(new methods().getSystemTime());
            int price = Integer.parseInt(good.getPrice())*Integer.parseInt(item.getNum());
            order.setTotal(String.valueOf(price));
            orderService.save(order);
        });
        cartService.remove(new QueryWrapper<Cart>().eq("userid",userid));
        return new Result(200,"订单提交成功！");
    }

}
